<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Purchase\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Purchase\Entity\Order;

class OrderRepository extends EntityRepository
{
    /**
     * 获取采购订单的sql
     * @param array $search
     * @return \Doctrine\ORM\Query
     */
    public function findAllOrder(array $search = []): \Doctrine\ORM\Query
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('o', 's')
            ->from(Order::class, 'o')
            ->join('o.oneSupplier', 's')
            ->orderBy('o.pOrderId', 'DESC');

        $query = $this->querySearchData($search, $query);

        return $query->getQuery();
    }

    /**
     * 获取最大采购订单id
     * @return float|int|mixed|string
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function getMaxOrderId()
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('MAX(o.pOrderId) as maxOrderId')->from(Order::class, 'o');

        $maxId = $query->getQuery()->getSingleScalarResult();

        return $maxId == null ? 1 : $maxId + 1;
    }

    private function querySearchData($search, QueryBuilder $queryBuilder): QueryBuilder
    {
        if(isset($search['start_amount']) && $search['start_amount'] > 0)               $queryBuilder->andWhere($queryBuilder->expr()->gte('o.pOrderAmount', $search['start_amount']));
        if(isset($search['end_amount']) && $search['end_amount'] > 0)                   $queryBuilder->andWhere($queryBuilder->expr()->lte('o.pOrderAmount', $search['end_amount']));
        if(!empty($search['p_order_sn']))                                               $queryBuilder->andWhere($queryBuilder->expr()->like('o.pOrderSn', "'%".$search['p_order_sn']."%'"));
        if(!empty($search['supplier_contacts']))                                        $queryBuilder->andWhere($queryBuilder->expr()->like('o.supplierContacts', "'%".$search['supplier_contacts']."%'"));
        if(!empty($search['supplier_phone']))                                           $queryBuilder->andWhere($queryBuilder->expr()->like('o.supplierPhone', "'%".$search['supplier_phone']."%'"));
        if(isset($search['supplier_id']) && $search['supplier_id'] > 0)                 $queryBuilder->andWhere($queryBuilder->expr()->eq('o.supplierId', $search['supplier_id']));
        if(!empty($search['payment_code']))                                             $queryBuilder->andWhere($queryBuilder->expr()->eq('o.paymentCode', ':code'))->setParameter('code', $search['payment_code']);
        if(isset($search['p_order_state']) && is_numeric($search['p_order_state']))     $queryBuilder->andWhere($queryBuilder->expr()->eq('o.pOrderState', $search['p_order_state']));
        if(isset($search['return_state']) && is_numeric($search['return_state']))       $queryBuilder->andWhere($queryBuilder->expr()->eq('o.returnState', $search['return_state']));

        $timeFiled = self::checkOrderTimeType($search);
        if(!empty($search['start_time']))       $queryBuilder->andWhere($queryBuilder->expr()->gte($timeFiled, ':startTime'))->setParameter('startTime', strtotime($search['start_time'].' 00:00:00'));
        if(!empty($search['end_time']))         $queryBuilder->andWhere($queryBuilder->expr()->lte($timeFiled, ':endTime'))->setParameter('endTime', strtotime($search['end_time'].' 23:59:59'));

        return $queryBuilder;
    }

    private static function checkOrderTimeType($search): string
    {
        if (!isset($search['time_type']) || !$search['time_type']) return 'o.noReviewTime';

        $timeFiled = 'o.noReviewTime';
        switch ($search['time_type']) {
            case -5:
                $timeFiled = 'o.returnFinishTime';
                break;
            case 1:
                $timeFiled = 'o.reviewTime';
                break;
            case 2:
                $timeFiled = 'o.waitWarehouseTime';
                break;
            case 3:
                $timeFiled = 'o.warehouseTime';
                break;
        }

        return $timeFiled;
    }
}